<template>
  <div class="page-container">
    <el-card class="main-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-content">
            <h2 class="header-title">机场信息管理</h2>
            <div class="search-bar">
              <el-input
                v-model="searchForm.cnnm"
                placeholder="机场中文名"
                clearable
                class="search-input"
                @keyup.enter="handleSearch"
              />
              <el-input
                v-model="searchForm.ennm"
                placeholder="机场英文名"
                clearable
                class="search-input"
                @keyup.enter="handleSearch"
              />
              <el-button
                type="primary"
                @click="handleSearch"
                class="action-button"
              >
                查询
              </el-button>
              <el-button
                @click="resetSearch"
                class="action-button"
              >
                重置
              </el-button>
              <el-button
                type="primary"
                @click="showAddDialog"
                v-if="isSuperAdmin"
                class="action-button"
              >
                添加机场
              </el-button>
            </div>
          </div>
        </div>
      </template>

      <div class="table-wrapper">
        <el-table
          :data="airportList"
          border
          stripe
          style="width: 100%"
          v-loading="loading"
          class="data-table"
          highlight-current-row
        >
          <el-table-column prop="APOT_APAT" label="机场属性" min-width="120" align="center" />
          <el-table-column prop="APOT_CODE" label="三字代码" min-width="120" align="center" />
          <el-table-column prop="APOT_CNNM" label="中文名" min-width="150" align="center" />
          <el-table-column prop="APOT_ENNM" label="英文名" min-width="150" align="center" />
          <el-table-column prop="APOT_AISO" label="状态" min-width="120" align="center">
            <template #default="{ row }">
              <el-tag :type="row.APOT_AISO === '0' ? 'success' : 'danger'" effect="light">
                {{ row.APOT_AISO === '0' ? '开启' : '关闭' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="APOT_APSN" label="航站简称" width="120" align="center" />
          <el-table-column label="操作" width="120" align="center" fixed="right">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button type="primary" size="small" @click="handleEdit(row)" plain>编辑</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container" :class="{ 'sticky-pagination': airportList.length >= pagination.pageSize }">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            class="right-aligned-pagination"
          />
        </div>
      </div>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%" class="custom-dialog">
      <el-form :model="airportForm" :rules="rules" ref="airportFormRef" label-width="100px">
        <el-form-item label="机场属性" prop="APOT_APAT">
          <el-input v-model="airportForm.APOT_APAT" />
        </el-form-item>
        <el-form-item label="三字代码" prop="APOT_CODE">
          <el-input v-model="airportForm.APOT_CODE" maxlength="3" show-word-limit />
        </el-form-item>
        <el-form-item label="中文名" prop="APOT_CNNM">
          <el-input v-model="airportForm.APOT_CNNM" />
        </el-form-item>
        <el-form-item label="英文名" prop="APOT_ENNM">
          <el-input v-model="airportForm.APOT_ENNM" />
        </el-form-item>
        <el-form-item label="状态" prop="APOT_AISO">
          <el-select v-model="airportForm.APOT_AISO" style="width: 100%">
            <el-option label="开启" value="0" />
            <el-option label="关闭" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="航站简称" prop="APOT_APSN">
          <el-input v-model="airportForm.APOT_APSN" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false" class="cancel-btn" size="large">
            <span>取消</span>
          </el-button>
          <el-button type="primary" @click="submitForm" class="confirm-btn" size="large">
            <span>确认</span>
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { FlightApi } from '@/api/flight'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const store = useStore()
const loading = ref(false)
const airportList = ref([])
const dialogVisible = ref(false)
const isAdd = ref(true)
const airportFormRef = ref(null)

const airportForm = ref({
  APOT_CODE: '',
  APOT_APAT: '',
  APOT_CNNM: '',
  APOT_ENNM: '',
  APOT_AISO: '0',
  APOT_APSN: ''
})

const searchForm = ref({
  cnnm: '',
  ennm: ''
})

const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const rules = {
  APOT_CODE: [
    { required: true, message: '请输入机场三字代码', trigger: 'blur' },
    { min: 3, max: 3, message: '机场代码必须为3个字符', trigger: 'blur' }
  ],
  APOT_CNNM: [
    { required: true, message: '请输入机场中文名', trigger: 'blur' }
  ],
  APOT_ENNM: [
    { required: true, message: '请输入机场英文名', trigger: 'blur' }
  ],
  APOT_AISO: [
    { required: true, message: '请选择机场状态', trigger: 'change' }
  ]
}

const fetchAirportList = async () => {
  try {
    loading.value = true
    let response

    if (searchForm.value.cnnm) {
      response = await FlightApi.getAirportsByCnName(
        searchForm.value.cnnm,
        pagination.value.currentPage,
        pagination.value.pageSize
      )
    } else if (searchForm.value.ennm) {
      response = await FlightApi.getAirportsByEnName(
        searchForm.value.ennm,
        pagination.value.currentPage,
        pagination.value.pageSize
      )
    } else {
      response = await FlightApi.getAirports(
        pagination.value.currentPage,
        pagination.value.pageSize
      )
    }

    airportList.value = response.data || []
    pagination.value.total = response.totalRecords || 0
  } catch (error) {
    ElMessage.error('获取机场信息失败: ' + error.message)
    console.error('获取机场信息失败:', error)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.value.currentPage = 1
  fetchAirportList()
}

const resetSearch = () => {
  searchForm.value = {
    cnnm: '',
    ennm: ''
  }
  pagination.value.currentPage = 1
  fetchAirportList()
}

const handleSizeChange = (val) => {
  pagination.value.pageSize = val
  fetchAirportList()
}

const handleCurrentChange = (val) => {
  pagination.value.currentPage = val
  fetchAirportList()
}

const showAddDialog = () => {
  isAdd.value = true
  airportForm.value = {
    APOT_CODE: '',
    APOT_APAT: '',
    APOT_CNNM: '',
    APOT_ENNM: '',
    APOT_AISO: '0',
    APOT_APSN: ''
  }
  dialogVisible.value = true
}

const handleEdit = (row) => {
  isAdd.value = false
  airportForm.value = { ...row }
  dialogVisible.value = true
}

const submitForm = async () => {
  try {
    await airportFormRef.value.validate()

    const dto = {
      apotCode: airportForm.value.APOT_CODE,
      apotApat: airportForm.value.APOT_APAT,
      apotCnnm: airportForm.value.APOT_CNNM,
      apotEnnm: airportForm.value.APOT_ENNM,
      apotAiso: airportForm.value.APOT_AISO,
      apotApsn: airportForm.value.APOT_APSN
    }

    if (isAdd.value) {
      await axios.post('http://localhost:8081/flightUpdate/addAirportInfo', dto)
      ElMessage.success('添加成功')
    } else {
      await axios.put('http://localhost:8081/flightUpdate/updateAirportInfo', dto)
      ElMessage.success('更新成功')
    }

    dialogVisible.value = false
    await fetchAirportList() // 确保更新后重新加载数据
  } catch (error) {
    if (error.name !== 'ValidationError') {
      console.error('操作失败:', error)
      ElMessage.error('操作失败: ' + (error.message || '未知错误'))
    }
  }
}

const dialogTitle = computed(() => isAdd.value ? '添加机场' : '编辑机场')
const isSuperAdmin = computed(() => store.getters.isSuperAdmin)

onMounted(() => {
  fetchAirportList()
})
</script>

<style scoped>
.page-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 64px);
}

.main-card {
  border-radius: 8px;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: 100%;
  display: flex;
  flex-direction: column;
}

.table-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  position: relative;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  padding: 10px 0;
  background: #fff;
  border-top: 1px solid var(--el-border-color-light);
}

.right-aligned-pagination {
  display: flex;
  justify-content: flex-end;
  width: 100%;
}

.right-aligned-pagination :deep(.el-pagination__total),
.right-aligned-pagination :deep(.el-pagination__sizes),
.right-aligned-pagination :deep(.el-pagination__jump) {
  margin-left: 10px;
}

.right-aligned-pagination :deep(.el-pagination__jump) {
  margin-left: 10px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .right-aligned-pagination {
    flex-wrap: wrap;
    justify-content: flex-end;
  }

  .right-aligned-pagination :deep(.el-pagination__total),
  .right-aligned-pagination :deep(.el-pagination__sizes),
  .right-aligned-pagination :deep(.el-pagination__jump) {
    margin: 5px 0;
    width: 100%;
    justify-content: flex-end;
  }
}

@media (max-width: 576px) {
  .right-aligned-pagination :deep(.btn-prev),
  .right-aligned-pagination :deep(.btn-next),
  .right-aligned-pagination :deep(.more) {
    display: none;
  }
}

.sticky-pagination {
  position: sticky;
  bottom: 0;
  z-index: 1;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.action-button {
  white-space: nowrap;
  padding: 8px 15px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.header-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  white-space: nowrap;
}

.search-bar {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: nowrap;
}

.search-input {
  width: 180px;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .search-bar {
    gap: 8px;
  }
  .search-input {
    width: 150px;
  }
}

@media (max-width: 992px) {
  .header-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  .search-bar {
    width: 100%;
    flex-wrap: wrap;
  }
  .search-input {
    width: calc(50% - 5px);
  }
}

@media (max-width: 768px) {
  .pagination-container {
    width: 100%;
    overflow-x: auto;
  }
}

@media (max-width: 576px) {
  .search-input {
    width: 100%;
  }
  .action-button {
    width: 100%;
  }

  .el-pagination :deep(.btn-prev),
  .el-pagination :deep(.btn-next),
  .el-pagination :deep(.more) {
    display: none;
  }
}
</style>
